package myfs

import (
	"context"
	"fmt"
	"os"
	"syscall"

	"github.com/hanwen/go-fuse/v2/fs"
	"github.com/hanwen/go-fuse/v2/fuse"
)

type ReadOnlyFile struct {
}

type FileInode struct {
	fs.Inode
	fs.MemRegularFile
}

func NewFileInode(b []byte) *FileInode {
	return &FileInode{
		MemRegularFile: fs.MemRegularFile{
			Data: b,
			Attr: fuse.Attr{
				Mode: 0444, // 只读权限
			},
		},
	}
}

func (sf *FileInode) Getattr(ctx context.Context, fh fs.FileHandle, out *fuse.AttrOut) syscall.Errno {
	// 每次读取文件时，打印进程信息
	fmt.Println("\n--------------------------- Getattr called -------------------")

	// 从上下文中获取 fuse 的上下文信息
	fuseCtx, ok := fuse.FromContext(ctx)
	if ok {
		fmt.Println("Read/gid, uid, pid:", fuseCtx.Gid, fuseCtx.Uid, fuseCtx.Pid)

		// 获取并打印进程的可执行文件路径
		exePath, err := GetExecutablePathByPID(int(fuseCtx.Pid))
		if err != nil {
			fmt.Println("Error getting executable path:", err)
		} else {
			fmt.Println("Executable path:", exePath)
		}

		if exePath == "/usr/bin/head" {
			return sf.MemRegularFile.Getattr(ctx, fh, out)
		}
	}

	out.Attr = fuse.Attr{Size: 0}
	return fs.OK
}

// GetExecutablePathByPID 通过PID获取进程的可执行文件路径
func GetExecutablePathByPID(pid int) (string, error) {
	// 获取进程的 /proc/{pid}/exe 文件
	exePath := fmt.Sprintf("/proc/%d/exe", pid)

	// 读取符号链接，获取可执行文件的路径
	path, err := os.Readlink(exePath)
	if err != nil {
		return "", fmt.Errorf("failed to get executable path: %w", err)
	}
	return path, nil
}
